<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>
    <BasicTable title="学生列表" titleTooltip="关注永雏塔菲喵，关注永雏塔菲谢谢喵" :columns="columns" :request="loadDataTable"
      :row-key="(row) => row.id" ref="actionRef" :actionColumn="actionColumn" :scroll-x="1360"
      @update:checked-row-keys="onCheckedRow">
      <template #tableTitle>
        <n-button type="primary" @click="addTable">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          新建
        </n-button>
      </template>
      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" title="新建">
      <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="left" :label-width="80" class="py-4">
        <n-form-item label="学号" path="SID">
          <n-input placeholder="请输入名称" v-model:value="formParams.SID" />
        </n-form-item>
        <n-form-item label="姓名" path="name">
          <n-input placeholder="请输入名称" v-model:value="formParams.name" />
        </n-form-item>
        <n-form-item label="性别" path="sex">
          <n-select v-model:value="formParams.sex" :options="sexOptions" />
        </n-form-item>
        <n-form-item label="学院" path="academyID">
          <n-select v-model:value="formParams.academyID" :options="academyOptions"
            @update:value="handleFormAcademyUpdate"></n-select>
        </n-form-item>
        <n-form-item label="专业" path="majorID">
          <n-select v-model:value="formParams.majorID" :options="formMajorOptions"
            @update:value="handleFormMajorUpdate"></n-select>
        </n-form-item>
        <n-form-item label="班级" path="claseID">
          <n-select v-model:value="formParams.claseID" :options="formClaseOptions"></n-select>
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
    <n-modal v-model:show="showEditModal" :show-icon="false" preset="dialog" title="编辑">
      <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="left" :label-width="80" class="py-4">
        <n-form-item label="学号" path="SID">
          <n-input placeholder="请输入名称" v-model:value="formParams.SID" />
        </n-form-item>
        <n-form-item label="姓名" path="name">
          <n-input placeholder="请输入名称" v-model:value="formParams.name" />
        </n-form-item>
        <n-form-item label="性别" path="sex">
          <n-select v-model:value="formParams.sex" :options="sexOptions" />
        </n-form-item>
        <n-form-item label="学院" path="academyID">
          <n-select v-model:value="formParams.academyID" :options="academyOptions"
            @update:value="handleFormAcademyUpdate"></n-select>
        </n-form-item>
        <n-form-item label="专业" path="majorID">
          <n-select v-model:value="formParams.majorID" :options="formMajorOptions"
            @update:value="handleFormMajorUpdate"></n-select>
        </n-form-item>
        <n-form-item label="班级" path="claseID">
          <n-select v-model:value="formParams.claseID" :options="formClaseOptions"></n-select>
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showEditModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmEditForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
import { reactive, ref, h, onMounted } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { getTableList } from '@/api/manager/studentManage/list';
import { columns } from './studentColumns';
import { SelectOption, useDialog, useMessage } from 'naive-ui';
import { PlusOutlined } from '@vicons/antd';
import { http } from '@/utils/http/axios';

const sexOptions: SelectOption[] = [
  {
    'label': '男',
    'value': '0'
  }, {
    'label': '女',
    'value': '1'
  }
]
const showModal = ref(false);
const showEditModal = ref(false);
const formBtnLoading = ref(false);
const formRef: any = ref(null);
const formParams = reactive({
  SID: null,
  name: null,
  sex: null,
  academyID: null,
  majorID: null,
  claseID: null,
});
const formMajorOptions: any = ref<SelectOption[]>([]);
const formClaseOptions = ref<SelectOption[]>([]);

const rules = {
  SID: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入学号',
  },
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入姓名',
  },
  sex: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择性别',
  }

};

const message = useMessage();
const dialog = useDialog();
const actionRef = ref();

function confirmForm(e) {
  e.preventDefault();
  formBtnLoading.value = true;
  formRef.value.validate((errors) => {
    if (!errors) {
      //message.success('新建成功');
      let params = formParams;
      http.request({
        url: '/manager/student_manage/addStudent',
        method: 'post',
        params
      }).then(
        () => {
          message.success('成功');
          showModal.value = false;
          reloadTable();
        }
      );
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}

function confirmEditForm(e) {
  e.preventDefault();
  formBtnLoading.value = true;
  formRef.value.validate((errors) => {
    if (!errors) {
      //message.success('新建成功');
      let params = formParams;
      http.request({
        url: '/manager/student_manage/editStudent',
        method: 'post',
        params
      }).then(
        () => {
          message.success('成功');
          showEditModal.value = false;
          reloadTable();
        }
      );
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}

const params = reactive({
  pageSize: 10,
  SID: null,
  academyID: null,
  majorID: null,
  claseID: null
});

const actionColumn = reactive({
  width: 150,
  title: '操作',
  key: 'action',
  fixed: 'right',
  align: 'center',
  render(record) {
    return h(TableAction, {
      style: 'button',
      actions: createActions(record),
    });
  },
});


function createActions(record) {
  return [
    {
      label: '删除',
      icon: 'ic:outline-delete-outline',
      onClick: handleDelete.bind(null, record),
      // 根据业务控制是否显示 isShow 和 auth 是并且关系
      ifShow: () => {
        return true;
      },
      // 根据权限控制是否显示: 有权限，会显示，支持多个
      auth: ['basic_list'],
    },
    {
      label: '修改',
      onClick: handleEdit.bind(null, record),
      ifShow: () => {
        return true;
      },
      auth: ['basic_list'],
    },
  ];
}

const loadDataTable = async (res) => {
  return await getTableList({ ...params, ...res });
};


const academyOptions = ref<SelectOption[]>([]);
const majorOptions = ref<SelectOption[]>([]);
const claseOptions = ref<SelectOption[]>([]);
const isClaseLoading = ref(false);

onMounted(
  async () => {
    const academyMajorInfo = ref();
    academyMajorInfo.value = await http.request({
      url: '/manager/academy_major_manage/list',
      method: 'get',
    });
    academyMajorInfo.value.forEach(element => {
      academyOptions.value.push({
        label: element['academyName'],
        value: element['academyID'],
        majorList: ((element) => {
          let arr: any = [];
          element['majorList'].forEach(element => {
            arr.push(
              {
                label: element['majorName'],
                value: element['majorID'],
              })
          });
          return arr;
        })(element),
      });
    });
    //获取学院信息
  })

function onCheckedRow(rowKeys) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}

function handleDelete(record) {
  console.log(record);
  dialog.info({
    title: '提示',
    content: `您想删除${record.name}`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      //message.success('删除成功');
      http.request({
        url: '/manager/student_manage/deleteStudent',
        method: 'get',
        params: { SID: record['SID'] }
      }
      ).then(
        () => {
          message.success('成功');
          reloadTable();
        }
      );
    },
    onNegativeClick: () => { },
  });
}

function handleEdit(record) {
  console.log(record);
  formParams['SID'] = record['SID'];
  formParams['name'] = record['name'];
  formParams['sex'] = record['sex'].toString();
  formParams['academyID'] = record['academyID'];
  formMajorOptions.value = [
    {
      label: '',
      value: ''
    }
  ];
  if (record['academyID'] != null) {
    academyOptions.value.forEach(element => {
      if (element['value'] == record['academyID']) {
        formMajorOptions.value = element['majorList'];
      }
    });
  }
  formParams['majorID'] = record['majorID'];
  handleFormMajorUpdate();
  formParams['claseID'] = record['claseID'];
  showEditModal.value = true;
}


function handleFormAcademyUpdate(e: any, s: any) {
  e;
  if (s) {
    formMajorOptions.value = s['majorList'];
  } else {
    formMajorOptions.value = [
      {
        label: '',
        value: ''
      }
    ];
  }
  formParams.majorID = null;
  formParams.claseID = null;
}

async function handleFormMajorUpdate() {
  formParams['claseID'] = null;
  //清空专业字段
  let params = formParams;
  let claseInfo = await http.request({
    url: '/manager/clase_manage/list',
    method: 'get',
    params
  })
  formClaseOptions.value = [];
  claseInfo.forEach(element => {
    formClaseOptions.value.push({
      label: element['claseName'],
      value: element['claseID'],
    });
  });
}

const schemas: FormSchema[] = [
  {
    field: 'SID',
    component: 'NInputNumber',
    label: '学号',
    componentProps: {
      placeholder: '请输入学号',
      showButton: false,
      onInput: (e: any) => {
        console.log(e);
      },
    },
  }, {
    field: 'academyID',
    component: 'NSelect',
    label: '学院',
    componentProps: {
      placeholder: '请选择学院',
      //remote:true,
      value: ref(null),
      options: academyOptions,
      onUpdateValue: (e: any, s: any) => {
        if (s) {
          majorOptions.value = s['majorList'];
        } else {
          majorOptions.value = [
            {
              label: '',
              value: ''
            }
          ];
        }
        let formValue = getFieldsValue();
        formValue['academyID'] = e;
        formValue['majorID'] = null;
        formValue['claseID'] = null;
        //清空专业字段
        setFieldsValue(formValue);

      },
      onClear: () => {
        majorOptions.value = [];
      }
    }
  },
  {
    field: 'enterYear',
    component: 'NDatePicker',
    label: '年级',
    componentProps: {
      placeholder: '请选择年级',
      type: 'year',
      format: 'yyyy',
      defaultValue: null,
      onUpdateValue: async (e: any) => {
        let formValue = getFieldsValue();
        formValue['enterYear'] = e;
        formValue['claseID'] = null;
        //清空专业字段
        setFieldsValue(formValue);
        let params = getFieldsValue();
        params['enterYear'] = new Date(e).getFullYear();
        let claseInfo = await http.request({
          url: '/manager/clase_manage/list',
          method: 'get',
          params
        });

        claseOptions.value = [];
        claseInfo.forEach(element => {
          claseOptions.value.push({
            label: element['claseName'],
            value: element['claseID'],
          });
        });
      },
    }
  }, {
    field: 'majorID',
    component: 'NSelect',
    label: '专业',
    componentProps: {
      placeholder: '请选择专业',
      options: majorOptions,
      onUpdateValue: async (e: any) => {
        let formValue = getFieldsValue();
        formValue['majorID'] = e;
        formValue['claseID'] = null;
        //清空专业字段
        setFieldsValue(formValue);
        let params = getFieldsValue();
        if (params['enterYear'] != null) {
          params['enterYear'] = new Date(params['enterYear']).getFullYear();
        }
        params['majorID'] = e;
        let claseInfo = await http.request({
          url: '/manager/clase_manage/list',
          method: 'get',
          params
        });
        claseOptions.value = [];
        claseInfo.forEach(element => {
          claseOptions.value.push({
            label: element['claseName'],
            value: element['claseID'],
          });
        });
      },
    }
  },

  {
    field: 'claseID',
    component: 'NSelect',
    label: '班级',
    componentProps: {
      placeholder: '请选择班级',
      loading: isClaseLoading,
      options: claseOptions
    }
  }
];

function addTable() {
  showModal.value = true;
}

const [register, { getFieldsValue, setFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:4 xl:5 2xl:5' },
  labelWidth: 80,
  schemas,
});

function handleSubmit(values: Recordable) {
  params['academyID'] = values['academyID'];
  params['majorID'] = values['majorID'];
  params['claseID'] = values['claseID'];
  reloadTable();
}

function handleReset(values: Recordable) {
  console.log(values);
}
</script>

<style lang="less" scoped>
</style>

